import { define } from 'cydon'
import { CPagination } from './CPagination'
import { DataFilter } from './DataFilter'
import { Item } from '../type'
import { CTable } from './CTable'
import { hexColor, processData } from '../util'
import { fill, updateItems, add } from '../game'
import { names } from '../defs'
import { world } from '../store'
import { updateOnVisable } from '../tino'

/** 是否可丢弃 */
const canDrop = (item: Item) =>
	item.selected && !item.name.includes('废料')

/**
 * @element item-table
 * 物品表格
 */
@define('item-table')
export class ItemTable extends CTable<Item> {
	static observedAttributes = super.observedAttributes

	/** 物品列表 */
	list!: Item[]

	/** 选中的块号 */
	selected = -1

	/** 批量设置物品数量 */
	count = 999

	/** 丢弃数量 */
	dropCount = 1

	/** 丢弃比例% */
	dropRate = 100

	/** 模式 */
	mode = 0

	/** 全选 */
	get selectAll() {
		return this.list.every(x => x.selected)
	}
	set selectAll(value) {
		this.list.forEach(x => x.selected = value)
	}

	connectedCallback() {
		this.list = names.map(name => ({
			name,
			amount: 0,
			delta: 0,
			capacity: 0
		}))
		this.mode = world.mode
		super.connectedCallback()
		// TODO: 重构
		//this.items = this.list
		//this.list = [...this.items]
		this.filter!.filters.push({
			key: 'amount',
			op: 2,
			value: '0',
			conj: 0,
			valid: true
		})
		updateOnVisable(this, () => this.updateContents(this.page, this.filter))
	}

	/** 获取增量颜色 */
	getColor(n: number, delta: number) {
		const s = 2 * Math.atan(6 * Math.log((n + delta) / n)) / Math.PI
		return '#' + hexColor(s > 0 ? [0, s, 0] : [-s, 0, 0])
	}

	/** 更新内容 */
	async updateContents(p: CPagination, f?: DataFilter) {
		updateItems(this.list, this.selected)
		this.items = [...processData(this.list, p, f)]
	}

	/** 按数量丢弃选中物品 */
	dropByCount() {
		for (const item of this.items) {
			if (canDrop(item)) {
				add(item.name, -this.dropCount, this.selected)
			}
		}
	}

	/** 按比例丢弃选中物品 */
	dropByRate() {
		const rate = this.dropRate / 100
		for (const item of this.items) {
			if (canDrop(item)) {
				add(item.name, -Math.ceil(item.amount * rate), this.selected)
			}
		}
	}

	/** 设置选中物品数量 */
	fill() {
		fill(this.list, this.selected, this.count)
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'item-table': ItemTable
	}
}
